package com.woniu.utils;

import com.woniu.service.PermissionService;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

@Component
public class TokenPermissionInterceptor implements HandlerInterceptor {

    @Resource
    private PermissionService permissionService;


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String requestURI = request.getRequestURI();

        // 1. 放行登录接口
        if (requestURI.equals("/staff/login")) {
            return true;
        }

        // 2. 从token头获取用户ID
        Integer staffId = getStaffIdFromToken(request);
        if (staffId == null) {
            sendError(response, "未登录或token无效");
            return false;
        }

        // 3. 超级管理员放行
        if (staffId == 1) {
            return true;
        }

        // 4. 检查权限
        String requiredPermission = getRequiredPermission(requestURI, request.getMethod());
        if (requiredPermission != null) {
            ResponseUtil checkResult = permissionService.checkUserPermission(staffId, requiredPermission);

            if (checkResult.getCode().equals(200)) {
                Boolean hasPermission = (Boolean) checkResult.getObj();
                if (!hasPermission) {
                    sendError(response, "没有操作权限");
                    return false;
                }
            } else {
                sendError(response, "权限检查失败: " + checkResult.getMsg());
                return false;
            }
        }

        return true;
    }


    private Integer getStaffIdFromToken(HttpServletRequest request) {
        // 从 token 头获取，不是 Authorization
        String token = request.getHeader("token");
        System.out.println("=== 拦截器调试信息 ===");
        System.out.println("请求URL: " + request.getRequestURI());
        System.out.println("Token头: " + token);

        if (token == null || token.trim().isEmpty()) {
            System.out.println("Token为空");
            return null;
        }

        try {
            if (!JWTUtil.verifyToken(token)) {
                System.out.println("Token验证失败");
                return null;
            }

            Integer staffId = JWTUtil.getUserId(token);
            System.out.println("解析出的用户ID: " + staffId);
            return staffId;

        } catch (Exception e) {
            System.out.println("Token解析异常: " + e.getMessage());
            e.printStackTrace();
            return null;
        }
    }


    private String getRequiredPermission(String url, String method) {
        // 员工管理权限
        if (url.equals("/staff/findAll")) return "staff:findAll";
        if (url.equals("/staff/list")) return "staff:list";
        if (url.equals("/staff/del")) return "staff:delete";
        if (url.equals("/staff/insert")) return "staff:add";
        if (url.equals("/staff/update")) return "staff:edit";
        if (url.equals("/staff/selectAll")) return "staff:selectAll";

        // 权限管理权限
        if (url.startsWith("/per/")) return "permission:manage";
        // 床位管理权限
        if (url.equals("/bed/findAll")) return "bed:findAll";
        if (url.equals("/bed/update")) return "bed:update";
        if (url.equals("/bed/del")) return "bed:del";
        if (url.equals("/bed/insert")) return "bed:insert";


        // 设备管理权限
        if (url.equals("/equip/findAll")) return "equip:findAll";
        if (url.equals("/equip/find")) return "equip:find";
        if (url.equals("/equip/del")) return "equip:del";
        if (url.equals("/equip/insert")) return "equip:insert";
        if (url.equals("/equip/update")) return "equip:update";

        //  检查项目管理权限
        if (url.equals("/examItem/findAll")) return "examItem:findAll";
        if (url.equals("/examItem/list")) return "examItem:list";
        if (url.equals("/examItem/del")) return "examItem:del";
        if (url.equals("/examItem/insert")) return "examItem:insert";
        if (url.equals("/examItem/update")) return "examItem:update";


        //  手术项目管理权限
        if (url.equals("/surgeryItem/findAll")) return "surgeryItem:findAll";
        if (url.equals("/surgeryItem/list")) return "surgeryItem:list";
        if (url.equals("/surgeryItem/del")) return "surgeryItem:del";
        if (url.equals("/surgeryItem/insert")) return "surgeryItem:insert";
        if (url.equals("/surgeryItem/update")) return "surgeryItem:update";


        //  病房管理权限
        if (url.equals("/ward/findAll")) return "ward:findAll";
        if (url.equals("/ward/find")) return "ward:find";
        if (url.equals("/ward/del")) return "ward:del";
        if (url.equals("/ward/insert")) return "ward:insert";
        if (url.equals("/ward/update")) return "ward:update";

        // 患者检查权限
        if (url.equals("/patientExam/list")) return "patientExam:findAll";
        if (url.equals("/patientExam/search")) return "patientExam:list";
        if (url.equals("/patientExam/complete")) return "patientExam:complete";

        // 患者手术权限
        if (url.equals("/patientSurgery/list")) return "patientSurgery:findAll";
        if (url.equals("/patientSurgery/search")) return "patientSurgery:list";
        if (url.equals("/patientSurgery/complete")) return "patientSurgery:complete";
        if (url.equals("/patientSurgery/sync")) return "patientSurgery:sync";




        // 仪表盘权限
        if (url.equals("/api/dashboard/medical-rooms") && method.equals("GET")) return "dashboard:medical-rooms";
        if (url.equals("/api/dashboard/patient-beds") && method.equals("GET")) return "dashboard:patient-beds";

        // 医嘱管理权限
        if (url.matches("/doctor-order/\\d+") && method.equals("GET")) return "doctor-order:view";
        if (url.equals("/doctor-order") && method.equals("POST")) return "doctor-order:add";
        if (url.equals("/doctor-order") && method.equals("PUT")) return "doctor-order:update";

        // 护理记录权限
        if (url.matches("/nursing-record/\\d+") && method.equals("GET")) return "nursing-record:view";
        if (url.equals("/nursing-record") && method.equals("POST")) return "nursing-record:add";

        // 入院管理权限
        if (url.startsWith("/api/admission/resources") && method.equals("GET")) return "admission:resources";
        if (url.equals("/api/admission/process") && method.equals("POST")) return "admission:process";
        if (url.equals("/inpatient-app/reject") && method.equals("POST")) return "admission:reject";

        // 出院管理权限
        if (url.equals("/api/discharge/process") && method.equals("POST")) return "discharge:process";
        if (url.equals("/discharge/list") && method.equals("POST")) return "discharge:list";
        if (url.equals("/inpatientDischargeApp/list") && method.equals("POST")) return "discharge:list";
        if (url.equals("/inpatientDischargeApp/add") && method.equals("POST")) return "discharge:apply";

        // 住院记录权限
        if (url.equals("/inpatientRecord") && method.equals("GET")) return "inpatient-record:list";
        if (url.equals("/inpatient-app/list") && method.equals("POST")) return "inpatient-app:list";

        // 病例管理权限
        if (url.equals("/case/add") && method.equals("POST")) return "case:add";

        // 手术管理权限
        if (url.matches("/surgery-app/patient/\\d+") && method.equals("GET")) return "surgery-app:patient";
        if (url.equals("/surgery-app") && method.equals("POST")) return "surgery-app:add";
        if (url.equals("/surgery-item") && method.equals("GET")) return "surgery-item:all";

        // 药品管理权限
        if (url.equals("/drug/find") && method.equals("POST")) return "drug:find";
        if (url.equals("/drug/add") && method.equals("POST")) return "drug:add";
        if (url.equals("/drug/update") && method.equals("PUT")) return "drug:update";
        if (url.equals("/drug/delete") && method.equals("DELETE")) return "drug:delete";
        if (url.equals("/drug") && method.equals("GET")) return "drug:list";
        if (url.equals("/drugDistribute/add") && method.equals("POST")) return "drug-distribute:add";
        if (url.equals("/drugDistribute/add2") && method.equals("POST")) return "drug-distribute:add";

        // 患者管理权限
        if (url.equals("/patient/findAll") && method.equals("GET")) return "patient:list";

        // 挂号管理权限
        if (url.equals("/registration/find") && method.equals("POST")) return "registration:find";

        // 请假管理权限
        if (url.matches("/doctor/apply/.+") && method.equals("POST")) return "employee:apply";
        if (url.equals("/director/list") && method.equals("GET")) return "employee:list";

        // 医疗科室权限
        if (url.equals("/medicalRoom") && method.equals("GET")) return "medical-room:list";

        // 住院申请权限
        if (url.equals("/inpatientApplication") && method.equals("POST")) return "inpatient-app:add";

        return null;
    }

    /**
     * 返回错误信息
     */
    private void sendError(HttpServletResponse response, String message) throws Exception {
        response.setStatus(403);
        response.setContentType("application/json;charset=utf-8");
        response.getWriter().write("{\"success\":false,\"message\":\"" + message + "\"}");
    }
}
